from django.shortcuts import *
from django.http import *
from rest_framework import *
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.decorators import *
from app01 import models
import json
from app01.models import Maintenance, Worker, RoadCondition
from django.core.paginator import Paginator
from django.core import serializers
from django.contrib.auth.hashers import check_password
from app01.serializers import *

@api_view(['GET'])
def test(request):
    return JsonResponse({"code": 1,
                         "message": "成功测试登录后的内容"})
# # 注销视图
# def logout(request):
#     request.session.pop('is_login', None)
#     return redirect('/login/')  # 重定向到登录页面


def createMaintenance(request):
    if request.method == "POST":
        # 从请求中获取前端发送的数据
        # data = request.POST  # 如果前端使用 POST 请求发送数据
        # 或者使用以下方式获取 JSON 数据
        # import json
        try:
            data = json.loads(request.body)
            # 使用获取到的数据创建新的 Maintenance 对象并保存到数据库
            Maintenance.objects.create(
                maintenance_id=data.get("maintenance_id"),
                maintenance_road_section=RoadCondition.objects.filter(pk=data.get("maintenance_road_section")).first(),
                maintenance_road=data.get("maintenance_road"),
                maintenance_method=data.get("maintenance_method"),
                maintenance_cost=data.get("maintenance_cost"),
                maintenance_duration=data.get("maintenance_duration"),
                maintenance_approver=Worker.objects.filter(pk=data.get("maintenance_approver")).first(),
                maintenance_approve_time=data.get("maintenance_approve_time")
            )
            # 返回 JSON 响应，通知前端操作成功
            response_data = {"code": 1,
                             "message": "成功插入新数据"}
            return JsonResponse(response_data)
        except Exception as e:
            response_data = {"code": 0, "message": str(e)}
            return JsonResponse(response_data, status=400)
def deleteMaintenance(request):
    if request.method == "GET":
        try:
            maintenance = Maintenance.objects.get(pk=request.GET.get("maintenanceId"))
            maintenance.delete()
            # 返回 JSON 响应，通知前端操作成功
            response_data = {"code": 1, "message": "成功删除数据"}
            return JsonResponse(response_data)
        except Maintenance.DoesNotExist:
            response_data = {"code": 0, "message": "指定的数据不存在"}
            return JsonResponse(response_data, status=404)
        except Exception as e:
            response_data = {"code": 0, "message": str(e)}
            return JsonResponse(response_data, status=400)
def updateMaintenance(request):
    if request.method == "POST":
        try:
            data = json.loads(request.body)
            maintenance = Maintenance.objects.get(pk=data.get("maintenance_id"))
            # 更新字段，安全获取字段值并提供默认值
            # maintenance.maintenance_id = data.get("maintenance_id", maintenance.maintenance_id)
            if (data.get("maintenance_NewId", None) is not None):
                maintenance.maintenance_id = data.get("maintenance_NewId", None)
                oldMaintenance = Maintenance.objects.get(pk=data.get("maintenance_id"))
                oldMaintenance.delete()
            maintenance.maintenance_road_section = RoadCondition.objects.filter(
                pk=data.get("maintenance_road_section", maintenance.maintenance_road_section)).first()
            maintenance.maintenance_road = data.get("maintenance_road", maintenance.maintenance_road)
            maintenance.maintenance_method = data.get("maintenance_method", maintenance.maintenance_method)
            maintenance.maintenance_cost = data.get("maintenance_cost", maintenance.maintenance_cost)
            maintenance.maintenance_duration = data.get("maintenance_duration", maintenance.maintenance_duration)
            maintenance.maintenance_approver = Worker.objects.filter(
                pk=data.get("maintenance_approver", maintenance.maintenance_approver)).first()
            maintenance.maintenance_approve_time = data.get("maintenance_approve_time",
                                                            maintenance.maintenance_approve_time)
            maintenance.save()
            # 返回响应信息
            response_data = {"code": 1, "message": "成功更新数据"}
            return JsonResponse(response_data)
        except Maintenance.DoesNotExist:
            response_data = {"code": 0, "message": "指定的数据不存在"}
            return JsonResponse(response_data, status=404)
        except Exception as e:
            response_data = {"code": 0, "message": str(e)}
            return JsonResponse(response_data, status=400)
def maintenanceList(request):
    # 获取Maintenance模型的所有数据,可以改进为按照某个字段排序
    maintenance_list = Maintenance.objects.all().order_by('maintenance_id')
    # 创建分页对象，每页显示10条数据
    paginator = Paginator(maintenance_list, 1)
    # 获取当前页码，默认为1
    page = request.GET.get('page')
    # 获取当前页的数据
    maintenance_page = paginator.get_page(page)
    # 序列化数据
    data = serializers.serialize('json', maintenance_page)
    # 返回JSON响应
    response_data = {
        'code': 1,
        'data': data,
        'page': maintenance_page.number,
        'total-pages': paginator.num_pages
    }
    return JsonResponse(response_data, safe=False)
# 增加 Worker 数据
def createWorker(request):
    if request.method == "POST":
        try:
            data = json.loads(request.body)  # 获取 JSON 数据

            Worker.objects.create(
                worker_id=data.get("worker_id"),
                worker_name=data.get("worker_name"),
                worker_phone=data.get("worker_phone"),
                worker_password=data.get("worker_password"),
                worker_role=data.get("worker_role"),

            )

            # 返回 JSON 响应，通知前端操作成功
            response_data = {"code": 1,
                             "message": "成功插入新数据"}
            return JsonResponse(response_data)
        except Exception as e:
            response_data = {"code": 0, "message": str(e)}
            return JsonResponse(response_data, status=400)


# 删除 Worker 数据
def deleteWorker(request):
    try:
        # 获取请求头中携带的workerId并且删除
        data = request.GET
        worker = Worker.objects.get(pk=data.get("workerId"))
        worker.delete()

        # 返回 JSON 响应，通知前端操作成功
        response_data = {"code": 1, "message": "成功删除数据"}
        return JsonResponse(response_data)

    except Worker.DoesNotExist:
        response_data = {"code": 0, "message": "指定的数据不存在"}
        return JsonResponse(response_data, status=404)
    except Exception as e:
        response_data = {"code": 0, "message": str(e)}
        return JsonResponse(response_data, status=400)


# 更新 Worker 数据
def updateWorker(request):
    if request.method == "POST":
        data = json.loads(request.body)
        try:
            worker = Worker.objects.get(pk=data.get("worker_id"))

            # 如果NewId不为空，说明要修改主键id，因此要删除原本的记录，新建一条记录
            if data.get("worker_NewId", None) is not None:
                worker.worker_id = data.get("worker_NewId")
                oldWorker = Worker.objects.get(pk=data.get("worker_id"))
                oldWorker.delete()

            worker.worker_name = data.get("worker_name", worker.worker_name)
            worker.worker_phone = data.get("worker_phone", worker.worker_phone)
            worker.worker_password = data.get("worker_password", worker.worker_password)
            worker.worker_role = data.get("worker_role", worker.worker_role)

            worker.save()

            # 返回响应信息
            response_data = {"code": 1, "message": "成功更新数据"}
        except Worker.DoesNotExist:
            response_data = {"code": 0, "message": "指定的数据不存在"}
        except Exception as e:
            response_data = {"code": 0, "message": str(e)}
        return JsonResponse(response_data)


def workerList(request):
    # 获取所有的 Worker 数据
    worker_list = Worker.objects.all().order_by('worker_id')

    # 创建分页对象，每页显示10条数据
    paginator = Paginator(worker_list, 10)

    # 获取当前页码，默认为1
    page = request.GET.get('page')

    # 获取当前页的数据
    worker_page = paginator.get_page(page)

    # 序列化数据
    data = serializers.serialize('json', worker_page)

    # 返回JSON响应
    response_data = {
        'code': 1,
        'data': data,
        'page': worker_page.number,
        'total-pages': paginator.num_pages
    }

    return JsonResponse(response_data, safe=False)


# 增加 RoadCondition 数据
def createRoadCondition(request):
    if request.method == "POST":
        try:
            data = json.loads(request.body)  # 获取 JSON 数据

            new_road_condition = RoadCondition.objects.create(
                road_section_id=data.get("road_section_id"),
                road_name=data.get("road_name"),
                road_lane_num=data.get("road_lane_num"),
                road_admin_level=data.get("road_admin_level"),
                road_direction=data.get("road_direction"),
                road_start_point=data.get("road_start_point"),
                road_end_point=data.get("road_end_point"),
                road_length=data.get("road_length"),
                road_maintenance_unit=data.get("road_maintenance_unit"),
                road_technical_level=data.get("road_technical_level"),
                road_surface_type=data.get("road_surface_type"),
                road_location=data.get("road_location"),
                # road_town=data.get("road_town"),
                road_pqi=data.get("road_pqi"),
                road_pci=data.get("road_pci"),
                road_rqi=data.get("road_rqi"),
                road_pqi_level=data.get("road_pqi_level"),
                road_pci_level=data.get("road_pci_level"),
                road_rqi_level=data.get("road_rqi_level"),
                road_dr=data.get("road_dr"),
                road_iri=data.get("road_iri"),
            )
            new_road_condition.save()

            # 返回 JSON 响应，通知前端操作成功
            response_data = {"code": 1,
                             "message": "成功插入新数据"}
            return JsonResponse(response_data)
        except Exception as e:
            response_data = {"code": 0, "message": str(e)}
            return JsonResponse(response_data, status=400)


# 删除 RoadCondition 数据
def deleteRoadCondition(request):
    try:
        # 获取请求头中携带的roadId并且删除
        data = request.GET
        road_condition = RoadCondition.objects.get(pk=data.get("roadSectionId"))
        road_condition.delete()

        # 返回 JSON 响应，通知前端操作成功
        response_data = {"code": 1, "message": "成功删除数据"}
        return JsonResponse(response_data)

    except RoadCondition.DoesNotExist:
        response_data = {"code": 0, "message": "指定的数据不存在"}
        return JsonResponse(response_data, status=404)
    except Exception as e:
        response_data = {"code": 0, "message": str(e)}
        return JsonResponse(response_data, status=400)


# 更新 RoadCondition 数据
def updateRoadCondition(request):
    if request.method == "POST":
        data = json.loads(request.body)
        try:
            road_condition = RoadCondition.objects.get(pk=data.get("road_section_id"))

            # 如果NewId不为空，说明要修改主键id，因此要删除原本的记录，新建一条记录
            if data.get("road_section_NewId", None) is not None:
                road_condition.road_section_id = data.get("road_section_NewId")
                oldRoadCondition = RoadCondition.objects.get(pk=data.get("road_section_id"))
                oldRoadCondition.delete()

            road_condition.road_name = data.get("road_name", road_condition.road_name)
            road_condition.road_lane_num = data.get("road_lane_num", road_condition.road_lane_num)
            road_condition.road_admin_level = data.get("road_admin_level", road_condition.road_admin_level)
            road_condition.road_direction = data.get("road_direction", road_condition.road_direction)
            road_condition.road_start_point = data.get("road_start_point", road_condition.road_start_point)
            road_condition.road_end_point = data.get("road_end_point", road_condition.road_end_point)
            road_condition.road_length = data.get("road_length", road_condition.road_length)
            road_condition.road_location = data.get("road_location", road_condition.road_location)
            road_condition.road_maintenance_unit = data.get("road_maintenance_unit",
                                                            road_condition.road_maintenance_unit)
            road_condition.road_technical_level = data.get("road_technical_level", road_condition.road_technical_level)
            road_condition.road_surface_type = data.get("road_surface_type", road_condition.road_surface_type)
            road_condition.road_pqi = data.get("road_pqi", road_condition.road_pqi)
            road_condition.road_pci = data.get("road_pci", road_condition.road_pci)
            road_condition.road_rqi = data.get("road_rqi", road_condition.road_rqi)
            road_condition.road_pqi_level = data.get("road_pqi_level", road_condition.road_pqi_level)
            road_condition.road_pci_level = data.get("road_pci_level", road_condition.road_pci_level)
            road_condition.road_rqi_level = data.get("road_rqi_level", road_condition.road_rqi_level)
            road_condition.road_dr = data.get("road_dr", road_condition.road_dr)
            road_condition.road_iri = data.get("road_iri", road_condition.road_iri)
            road_condition.save()

            # 返回响应信息
            response_data = {"code": 1, "message": "成功更新数据"}
        except RoadCondition.DoesNotExist:
            response_data = {"code": 0, "message": "指定的数据不存在"}
        except Exception as e:
            response_data = {"code": 0, "message": str(e)}
        return JsonResponse(response_data)


def roadConditionList(request):
    # 获取所有的 RoadCondition 数据
    road_condition_list = RoadCondition.objects.all().order_by('road_section_id')

    # 创建分页对象，每页显示10条数据
    paginator = Paginator(road_condition_list, 10)

    # 获取当前页码，默认为1
    page = request.GET.get('page')

    # 获取当前页的数据
    road_condition_page = paginator.get_page(page)

    # 序列化数据
    data = serializers.serialize('json', road_condition_page)

    # 返回JSON响应
    response_data = {
        'code': 1,
        'data': data,
        'page': road_condition_page.number,
        'total-pages': paginator.num_pages
    }

    return JsonResponse(response_data, safe=False)


class MaintenanceViewSet(viewsets.ModelViewSet):
    queryset = Maintenance.objects.all()
    serializer_class = MaintenanceSerializer

    @action(detail=False, methods=['POST'])
    def search(self, request):
        try:
            # 获取请求中的字段名和对应的值
            field_name = request.data.get('type')
            field_value = request.data.get('value')
            # 根据字段名和值进行过滤
            if field_name and field_value:
                # 直接匹配字段名和值
                queryset = Maintenance.objects.filter(**{field_name: field_value})
                serializer = self.get_serializer(queryset, many=True)
                return Response(serializer.data)
            else:
                return Response(
                    {'error': 'Invalid request. 请提供正确的查询数据'},
                    status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class RoadConditionViewSet(viewsets.ModelViewSet):
    queryset = RoadCondition.objects.all()
    serializer_class = RoadConditionSerializer

    @action(detail=False, methods=['POST'])
    def search(self, request):
        try:
            # 获取请求中的字段名和对应的值
            field_name = request.data.get('type')
            field_value = request.data.get('value')
            # 根据字段名和值进行过滤
            if field_name and field_value:
                # 直接匹配字段名和值
                queryset = RoadCondition.objects.filter(**{field_name: field_value})
                serializer = self.get_serializer(queryset, many=True)
                return Response(serializer.data)
            else:
                return Response(
                    {'error': 'Invalid request. 请提供正确的查询数据'},
                    status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class WorkerViewSet(viewsets.ModelViewSet):
    queryset = Worker.objects.all()
    serializer_class = WorkerSerializer

    @action(detail=False, methods=['POST'])
    def search(self, request):
        try:
            # 获取请求中的字段名和对应的值
            field_name = request.data.get('type')
            field_value = request.data.get('value')
            # 根据字段名和值进行过滤
            if field_name and field_value:
                # 直接匹配字段名和值
                queryset = Worker.objects.filter(**{field_name: field_value})
                serializer = self.get_serializer(queryset, many=True)
                return Response(serializer.data)
            else:
                return Response(
                    {'error': 'Invalid request. 请提供正确的查询数据'},
                    status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(detail=False, methods=['POST'])
    def login(self, request):
        if request.method == 'POST':
            try:
                print(request.body)
                data = json.loads(request.body)
                name = data['worker_name']
                password = data['worker_password']
                print(name, password)
            except json.decoder.JSONDecodeError:
                return Response({'error': '请输入用户名和密码'}, status=status.HTTP_400_BAD_REQUEST)

            worker = Worker.objects.filter(worker_name=name).first()
            if worker and password == worker.worker_password:
                # Successful login
                request.session['worker_id'] = worker.worker_id
                request.session['is_login'] = True
                request.session.set_expiry(60 * 60)  # Set session timeout to 1 hour

                return Response(data={
                    'code': 1,
                    'msg': '成功登录'
                }, status=status.HTTP_200_OK)
            else:
                return Response(data={
                    'code': 0,
                    'msg': '登录失败，用户名和密码不正确'
                }, status=status.HTTP_401_UNAUTHORIZED)

        return Response(data={
            'code': 0,
            'msg': '登录失败'
        }, status=status.HTTP_405_METHOD_NOT_ALLOWED)

    @action(detail=False, methods=['GET'])
    def logout(self, request):
        if request.session.get('is_login', False):
            # Only perform logout if the user is logged in
            request.session.pop('is_login', None)
            request.session.pop('worker_id', None)

            return Response(data={
                'code': 1,
                'msg': '成功注销'
            }, status=status.HTTP_200_OK)
        else:
            return Response(data={
                'code': 0,
                'msg': '用户未登录'
            }, status=status.HTTP_401_UNAUTHORIZED)
